<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" v-model="UserInfo.query" clearable @clear="getUserList"
                        @change="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
            </el-row>
            <el-table :data="usersList" style="width: 100%" border stripe>
                <el-table-column type="index" width="180">
                </el-table-column>
                <el-table-column prop="username" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="email" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="mobile" label="电话">
                </el-table-column>
                <el-table-column prop="role_name" label="角色">
                </el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" active-color="#409eff" inactive-color="#e9edf0"
                            @change="swbtn(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showList(scope.row.id)">
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="delbtn(scope.row.id)">
                        </el-button>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="UserInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="UserInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 提示区域 -->
        <!-- 添加用户 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeForm">
            <!-- 主体区域 -->
            <el-form :model="person" :rules="addrules" ref="person" label-width="100px" class="demo-ruleForm"
                status-icon>
                <el-form-item label="用户名称" prop="username">
                    <el-input v-model="person.username"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="person.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="person.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="person.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addForm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editcloseForm">
            <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px" status-icon>
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editform">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { UserApi, swchangeApi, addUserApi, UserIdApi, editUserApi, delUserApi } from '@/api/index'
export default {
    data() {
        //邮箱的验证规则
        const checkEmail = (rule, value, callback) => {
            const regEmail = /^\w+@\w+(\.\w+)+$/
            if (regEmail.test(value)) {
                return callback()
            }
            callback(new Error('请输入合法的邮箱'))

        }
        const checkMobile = (rule, value, callback) => {
            const regMobile = /^1[34578]\d{9}$/
            if (regMobile.test(value)) {
                return callback()
            }
            callback(new Error('请输入正确的手机号码'))
        }
        return {
            UserInfo: {
                query: '',
                pagenum: 1,
                pagesize: 2,
            },
            usersList: [],
            total: 0,
            dialogVisible: false,
            editDialogVisible: false,
            editForm: {},
            person: {
                username: '',
                password: '',
                email: '',
                mobile: '',
            },
            addrules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '用户名长度在3-10个字符之间', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            },
            editFormrules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            }
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        async getUserList() {
            const { data: res } = await UserApi(
                { ...this.UserInfo }
            )
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
            this.total = res.data.total
            this.usersList = res.data.users
        },
        handleSizeChange(newsize) {
            this.UserInfo.pagesize = newsize
            this.getUserList()
        },
        handleCurrentChange(newCurre) {
            this.UserInfo.pagenum = newCurre
            this.getUserList()
        },
        async swbtn(val) {
            const { data: res } = await swchangeApi({
                url: `users/${val.id}/state/${val.mg_state}`,
                method: 'PUT'
            })
            if (res.meta.status !== 200) return this.$message.error('更新用户状态失败')
            this.$message.success('更新用户状态成功')
        },
        closeForm() {
            this.$refs.person.resetFields()
        },
        addForm() {
            this.$refs.person.validate(async valid => {
                if (!valid) return
                const { data: res } = await addUserApi({
                    url: 'users',
                    method: 'POST',
                    data: this.person
                })
                if (res.meta.status !== 201) return this.$message.error('更新用户状态失败')
                this.$message.success('更新用户状态成功')
            })
            this.dialogVisible = false
            this.getUserList()
        },
        async showList(id) {
            this.editDialogVisible = true
            console.log(id)
            const { data: res } = await UserIdApi({
                url: `users/${id}`,
            })
            if (res.meta.status !== 200) return this.$message.error('查询用户状态失败')
            this.$message.success('查询用户状态成功')
            this.editForm = res.data
        },
        editcloseForm() {
            this.$refs.editFormRef.resetFields()
        },
        editform() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await editUserApi({
                    method: 'PUT',
                    url: `users/${this.editForm.id}`,
                    data: {
                        email: this.editForm.email,
                        mobile: this.editForm.mobile,
                    }
                })
                console.log(res)
                if (res.meta.status !== 200) return this.$message.error('更新用户状态失败')
                this.$message.success('更新用户状态成功')
                this.editDialogVisible = false
                this.getUserList()
            })
        },
        async delbtn(id) {
            const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (res === 'cancel') return this.$message.info('已取消删除')
            const delres = await delUserApi({
                url: `users/${id}`,
                method: 'delete',
            })
            this.$message.success('已删除成功')
            this.getUserList()

        }
    }
}


</script>

<style scoped>
.el-card {
    margin-top: 20px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important
}

.el-button {
    margin-left: 15px;
}

.el-table {
    margin-top: 15px;
}

.el-pagination {
    margin-top: 15px;
}
</style>